package cn.itsource.campus.controller;

import cn.itsource.campus.domain.Teacher;
import cn.itsource.campus.service.ITeacherService;
import cn.itsource.campus.util.AjaxResult;
import cn.itsource.campus.util.ExcelUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * 老师控制器
 */
@RestController
@RequestMapping("/teacher")
public class TeacherController {
    @Autowired
    private ITeacherService teacherService;



    /**
     * 新增和修改接口
     * @param teacher  如果id为空就新增，否则做修改
     * @return  操作是否成功的结果值
     */
    @PutMapping
    public AjaxResult save(@RequestBody Teacher teacher){
        try{
            teacherService.save(teacher);
            return AjaxResult.ok();
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.fail(e.getMessage());
        }
    }

    /**
     * 删除老师接口
     * @param id  主键id
     * @return  操作是否成功的结果值
     */
    @DeleteMapping("/{id}")
    public AjaxResult delete(@PathVariable("id") Long id){
        try{
            teacherService.delete(id);
            return AjaxResult.ok();
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.fail(e.getMessage());
        }
    }

    /**
     * 查询单个老师接口
     * @param id  主键id
     * @return  操作是否成功的结果值
     */
    @GetMapping("/{id}")
    public AjaxResult get(@PathVariable("id") Long id){
        try{
            return AjaxResult.ok(teacherService.get(id));
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.fail(e.getMessage());
        }
    }


    /**
     * 导入excel数据
     * @return
     */
    @PostMapping("/importExcel")
    public AjaxResult importExcel(MultipartFile file){
        try{
            List<Teacher> teachers = ExcelUtil.importExcel(file, Teacher.class);
            //批量插入数据
            teacherService.batchSave(teachers);
            return AjaxResult.ok();
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.fail(e.getMessage());
        }
    }

    /**
     * 导出模板
     */
    @GetMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) throws IOException {
        ExcelUtil.exportExcel(teacherService.getAll(),"老师列表","老师",Teacher.class,
                "老师",response);
    }

    /**
     * 查询老师列表接口
     * @return  操作是否成功的结果值
     */
    @PatchMapping
    public AjaxResult getAll(){
        try{
            System.out.println("列表。。。。。。。。。。。。。。。。。。。。。。。。");
            return AjaxResult.ok(teacherService.getAll());
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.fail(e.getMessage());
        }
    }
}
